<?php

namespace app\admin\command;


use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use app\common\library\ImageCraw;
use \Exception;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Facebody\V20191230\Models\AddFaceEntityRequest; //人脸样本添加
use AlibabaCloud\SDK\Facebody\V20191230\Models\AddFaceAdvanceRequest; //人脸数据添加
use AlibabaCloud\SDK\Facebody\V20191230\Models\SearchFaceAdvanceRequest;//人脸搜索
use AlibabaCloud\SDK\Facebody\V20191230\Models\DeleteFaceEntityRequest; //人脸样本删除
use AlibabaCloud\SDK\Facebody\V20191230\Facebody;
use GuzzleHttp\Psr7\Stream;


class BroadcastAi extends Command
{
    protected $number;
    protected function configure()
    {
        $this
            ->setName('ai')
            ->setDescription('ai');
    }

    protected function execute(Input $input, Output $output)
    {
        $photo =Db::name('BroadcastAi')->where('status',1)->find();
        if(!empty($photo) && !empty($photo['image'])){

            $rlt = $this->SearchFaceAdvance($photo['image']);
            if($rlt['code'] == '200'){
                $avatar = [];
                if(isset($rlt['Data']['MatchList'])){
                    $matchlist = $rlt['Data']['MatchList'];
                    foreach ($matchlist as $key => $value) {
                        if(isset($value['FaceItems'])){
                            if($value['FaceItems'][0]['Confidence']>85){
                                $avatar[] = $value['FaceItems'][0]['EntityId'];
                            }
                        }
                    }
                }
                if(count($avatar)>0){
                    $avatars = implode(',',$avatar);
                    Db::name('BroadcastAi')->where('id',$photo['id'])->update(['remark'=>'运行任务完成，识别出'.count($avatar).'张头像','status'=>'2','avatars'=>$avatars]);
                }else{
                    Db::name('BroadcastAi')->where('id',$photo['id'])->update(['remark'=>'运行任务失败，未识别出图像','status'=>'3']);
                }
            }else{
                Db::name('BroadcastAi')->where('id',$photo['id'])->update(['remark'=>'运行任务失败，未识别出图像','status'=>'3']);
            }
        }else{
            Db::name('BroadcastAi')->where('id',$photo['id'])->update(['remark'=>'运行任务失败，未识别出图像','status'=>'3']);
        }
    }
    
    protected function SearchFaceAdvance($image){
        $config = get_addon_config('alioss');
        $aliConfig = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $config['accessKeyId'],
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $config['accessKeySecret']
        ]);
        // 访问的域名
        $aliConfig->endpoint = "facebody.cn-shanghai.aliyuncs.com";
        $faceBody = new Facebody($aliConfig);
        $file = fopen($config['cdnurl'].$image."?x-oss-process=image/resize,w_750,h_750,m_mfit", 'rb');
        $stream = new Stream($file);
        $searchFaceAdvanceRequest = new SearchFaceAdvanceRequest([
            "dbName" => "default",
            "imageUrlObject" => $stream,
            "limit" => 1,
            "MaxFaceNum"=>5
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $resp = $faceBody->searchFaceAdvance($searchFaceAdvanceRequest, $runtime);
            $respon =json_decode(
                Utils::toJSONString($resp->body),true
            );
            $respon['code']='200';
            return $respon;
        } catch (\Exception $exception) {
            # 获取整体报错信息
            echo Utils::toJSONString($exception);
            # 获取单个字段
            $respon['code']='500';
            return $respon;
        }
    }
}